package com.yuandian.middle.platform.utils;

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CommonUtils {

    public static String dateFormat = "yyyy-MM-dd HH:mm:ss";
    public static String dateFormatMinute = "yyyy-MM-dd HH:mm";

    /**
     * long类型除法，返回double，保留2位小数
     * @param number1
     * @param number2
     * @return
     */
    public static double longDiv(long number1, long number2) {
        DecimalFormat df = new DecimalFormat("0.0000");
        if (number2 == 0) {
            number2 = 1;
        }
        return Double.parseDouble(df.format((double)number1/number2));
    }

    /**
     * 在指定的时间上增加或较少对应的天数
     * @param date
     * @param day
     * @return
     */
    public static Date addDay(Date date, int day) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(c.DATE, day);
        return c.getTime();
    }

    /**
     * 日期格式转字符串
     * @param date
     * @param format
     * @return
     */
    public  static String dateFormatString(Date date, String format) {
        if (format == null || "".equals(format)) {
            format = dateFormat;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 字符串转日期格式
     * @param dateStr
     * @param format
     * @return
     */
    public static Date stringFormatDate(String dateStr, String format) {
        try {
            if (format == null || "".equals(format)) {
                format = dateFormat;
            }
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.parse(dateStr);
        } catch(ParseException e) {
            return null;
        }
    }

    /**
     * 在指定的时间上增加指定的分钟数，如果实负数，则代表减去分钟数
     * 例如：如minute是-15，即得到的时间是：该时间减去15分钟
     * @param date
     * @param minute
     * @return
     */
    public static Date addMinute(Date date, int minute){
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(c.MINUTE, minute);
        return c.getTime();
    }

    /**
     * 把字符串转换为时间戳（精确到秒）
     * @param dateStr
     * @param format
     * @return
     */
    public static long stringFormatTimestamp(String dateStr, String format) {
        if (format == null || "".equals(format)) {
            format = dateFormat;
        }
        SimpleDateFormat fd = new SimpleDateFormat(format);
        try {
            Date d = fd.parse(dateStr);
            return d.getTime()/1000;
        } catch (ParseException e) {
            return 0;
        }
    }

    /**
     * 把时间戳转换成指定的日期字符串
     * @param second
     * @param format
     * @return
     */
    public static String timestampFormatString(long second, String format){
        Date date = new Date();
        date.setTime(second * 1000);
        return dateFormatString(date, format);
    }

    /**
     * 将BigInteger整数转为ipv6
     * @param big
     * @return
     */
    public static String intToipv6(BigInteger big){
        String str = "";
        BigInteger ff = BigInteger.valueOf(0xffff);
        for (int i = 0; i < 8 ; i++){
            str = big.and(ff).toString(16) + ":" + str;
            big = big.shiftRight(16);
        }
        str = str.substring(0, str.length() - 1);
        return str.replaceFirst("(^|:)(0+(:|$)){2,8}", "::");
    }

    /**
     * 长整型ip转换为string
     *
     * @param long型ip
     * @return
     */
    public static String longToIpString(long ipLong) {
        long mask = 0xff;
        long num = 0;
        StringBuffer ipInfo = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            num = (ipLong >> ((3 - i) * 8)) & mask;
            ipInfo.append(num);
            if (i != 3) {
                ipInfo.append(".");
            }
        }
        return ipInfo.toString();
    }

    /**
     * ip转成整型
     *
     * @param ip
     *            ip地址（如：192.168.1.1）
     * @return
     */
    public static long ipStringToLong(String ip) {
        String[] parts = ip.split("\\.");
        if (parts == null || parts.length < 4){
            return -1;
        }
        long a = Long.parseLong(parts[0]);
        long b = Long.parseLong(parts[1]);
        long c = Long.parseLong(parts[2]);
        long d = Long.parseLong(parts[3]);
        return (a << 24) + (b << 16) + (c << 8) + d;
    }

    /**
     * ipv6的地址转为BigInteger整数
     * @param ipv6
     * @return
     */
    public static BigInteger ipv6ToInt(String ipv6) {
        int compressIndex = ipv6.indexOf("::");
        if (compressIndex != -1)
        {
            String part1s = ipv6.substring(0, compressIndex);
            String part2s = ipv6.substring(compressIndex + 1);
            BigInteger part1 = ipv6ToInt(part1s);
            BigInteger part2 = ipv6ToInt(part2s);
            int part1hasDot = 0;
            char ch[] = part1s.toCharArray();
            for (char c : ch)
            {
                if (c == ':')
                {
                    part1hasDot++;
                }
            }
            return part1.shiftLeft(16 * (7 - part1hasDot )).add(part2);
        }
        BigInteger big = BigInteger.ZERO;
        String[] str = ipv6.split(":");
        for (int i = 0; i < str.length; i++) {
            if (str[i].isEmpty())
            {
                str[i] = "0";
            }
            big = big.add(BigInteger.valueOf(Long.valueOf(str[i], 16))
                    .shiftLeft(16 * (str.length - i - 1)));
        }
        return big;
    }

    /**
     * 如果最后一个点的时间与结束时间相同，则去掉
     * @param map
     */
    public static void removeLastPoint(Map<String, Object> map, String endTime) {
        Object obj = map.get("resLabelTimeArr");
        if (obj != null) {
            List<String> list = (List<String>) obj;
            if (list != null && list.size() > 0) {
                String time = list.get(list.size() - 1);
                if (endTime.equals(time)) {
                    list.remove(list.size() - 1);
                    map.put("resLabelTimeArr", list);
                }
            }
        }
    }
}
